package com.qq.BFMRSE.encrypt;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import com.qq.BFMRSE.util.BFConstants;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
public class desEncrypt {
	private String desKeyPath;
	private byte[] ENCRYPTED_KEY; 
	public String getDesKeyPath(){
		return desKeyPath;
	}
	public void setDesKeyPath(String desKeyPath){
		this.desKeyPath=desKeyPath;
	}
	public desEncrypt(String desKeyPath){
		this.desKeyPath=desKeyPath;
		ENCRYPTED_KEY=getDesKey();
	}
	public byte[] getDesKey(){
	    //1.读取文件中的密钥  
        File file = new File(desKeyPath+File.separator+BFConstants.DESKEYFILENAME);  
        InputStream inputStream;
		try {
			inputStream = new FileInputStream(file);
			InputStreamReader inputStreamReader= new InputStreamReader(inputStream); //得到文件的字符流  
	        BufferedReader bufferedReader=new BufferedReader(inputStreamReader); //放入读取缓冲区  
	        String readd="";  
	        StringBuffer stringBuffer=new StringBuffer();  
	        while ((readd=bufferedReader.readLine())!=null) {  
	            stringBuffer.append(readd);  
	        }  
	        inputStream.close();  
	        String keystr=stringBuffer.toString();  
	        System.out.println(keystr+" -----> key读取成功");  //读取出来的key是编码之后的 要进行转码  
	          
	       //2.通过读取到的key  获取到key秘钥对象  
	        return HexBin.decode(keystr); 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
        
	}
	/**
	 * encrypt byte array
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private byte[]encrypt(byte []data,byte []key)throws Exception
	{
		DESKeySpec keySpec=new DESKeySpec(key);
		SecureRandom sc=new SecureRandom();
		SecretKeyFactory factory=SecretKeyFactory.getInstance(BFConstants.ALGORITHM);
		SecretKey seKey=factory.generateSecret(keySpec);
		Cipher cipher=Cipher.getInstance(BFConstants.ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, seKey,sc);
		return cipher.doFinal(data);
	}
	/**
	 * decrypt byte array data
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private byte[]decrypt(byte []data,byte[]key)throws Exception
	{
		DESKeySpec keySpec=new DESKeySpec(key);
		SecureRandom sc=new SecureRandom();
		SecretKeyFactory factory=SecretKeyFactory.getInstance(BFConstants.ALGORITHM);
		SecretKey seKey=factory.generateSecret(keySpec);
		Cipher cipher=Cipher.getInstance(BFConstants.ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, seKey,sc);
		return cipher.doFinal(data);
	}
	/**
	 * encrypt string
	 * @param data
	 * @return
	 */
	public String encrypt(String data)
	{
		byte[] result=null;
		try {
			result = encrypt(data.getBytes(), ENCRYPTED_KEY);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Base64.encodeBase64String(result);
	}
	/**
	 * decrypt string
	 * @param data
	 * @return
	 */
	public String decrypt(String data) throws Exception
	{
		byte[]result=decrypt(Base64.decodeBase64(data),ENCRYPTED_KEY);
		return new String(result);
	}
	/**
	 * encrypt file
	 * @param fle
	 * @return
	 */
	public void encrypt(File file,String desFile)throws Exception
	{
		DESKeySpec KeySpec=new DESKeySpec(ENCRYPTED_KEY);
		SecureRandom random=new SecureRandom();
		SecretKeyFactory factory=SecretKeyFactory.getInstance(BFConstants.ALGORITHM);
		SecretKey secretKey=factory.generateSecret(KeySpec);
		Cipher cipher=Cipher.getInstance(BFConstants.ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey,random);
		CipherInputStream cis=new CipherInputStream(new FileInputStream(file), cipher);
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File(desFile)));
		byte []temp=new byte[1024];
		int r=0;
		while(( r=cis.read(temp))>0)
		{
			bos.write(temp,0,r);
		}
		bos.close();
		cis.close();
	}
	public void descrypt(File file,String decFilePath)throws Exception
	{
		DESKeySpec KeySpec=new DESKeySpec(ENCRYPTED_KEY);
		SecureRandom random=new SecureRandom();
		SecretKeyFactory factory=SecretKeyFactory.getInstance(BFConstants.ALGORITHM);
		SecretKey secretKey=factory.generateSecret(KeySpec);
		Cipher cipher=Cipher.getInstance(BFConstants.ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, secretKey,random);
		CipherInputStream cis=new CipherInputStream(new FileInputStream(file), cipher);
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File(decFilePath)));
		byte []buffer=new byte[1024];
		int len=0;
		while((len=cis.read(buffer))>0){
			bos.write(buffer, 0, len);
		}
		bos.close();
		cis.close();
	}
	public int encryptAllFiles(String files,String desFile)
	{
		int flag=0;
		File docFile=new File(files);
		if(docFile.exists()&&docFile.isDirectory())
		{
			File desDir=new File(desFile);
			if(!desDir.exists())
			{
				desDir.mkdirs();
			}
			FileFilter filter=new FileFilter() {
				public boolean accept(File pathname) {
					// TODO Auto-generated method stub
					if(pathname.getName().toLowerCase().endsWith(".txt"))
					{
						return true;
					}
					return false;
				}
			};
			File[]txtFiles=docFile.listFiles(filter);
			for(int i=0;i<txtFiles.length;i++)
			{
				String filePath=desFile+File.separator+txtFiles[i].getName();
				try {
					encrypt(txtFiles[i],filePath);
					flag++;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
}
